package com.changgou.oauth.controller;

import com.changgou.common.pojo.Result;
import com.changgou.common.pojo.StatusCode;
import com.changgou.oauth.service.IUserLoginService;
import com.changgou.oauth.util.CookieUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @ClassName: UserLogin
 * @Auther: syq
 * @Date: 2021/7/14 09:44
 * @Version 1.0
 */
@RestController
@RequestMapping("/user")
public class UserLogin {
    private static final String grant_type = "password";
    private static final String cilenid = "changgou";
    private static final String secret = "changgou";
    @Autowired
    private IUserLoginService userLoginService;
    //Cookie存储的域名
    @Value("${auth.cookieDomain}")
    private String cookieDomain;

    //Cookie生命周期
    @Value("${auth.cookieMaxAge}")
    private int cookieMaxAge;

    @RequestMapping("/login")
    public Result<Map> login(String username, String password) {
        if (StringUtils.isEmpty(username)) {
            throw new RuntimeException("用户名不允许为空");
        }
        if (StringUtils.isEmpty(password)) {
            throw new RuntimeException("密码不允许为空");
        }
        Map<String, String> map = userLoginService.login(grant_type, username, password, cilenid, secret);
        saveCookie(map.get("access_token"));
        return new Result(true, StatusCode.OK, "生成令牌成功",map.get("access_token"));
    }

    /***
     * 将令牌存储到cookie
     * @param token
     */
    private void saveCookie(String token) {
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        CookieUtil.addCookie(response, cookieDomain, "/", "Authorization", token, cookieMaxAge, false);
    }
}
